<template lang="">
  <el-card class="box-card">
    <el-row>
      <el-col :span="6">
        <el-input v-model="queryInfo.query" placeholder="请输入内容" clearable>
          <el-button slot="append" icon="el-icon-search" @click="search"></el-button>
        </el-input>
      </el-col>
      <el-col :span="2">
        <el-button type="primary" @click='showAddUser'>添加用户</el-button>
      </el-col>
    </el-row>

    <el-table :data="users" stripe fit height="330" border style="width: 100%">
      <el-table-column type="index" width="50"> </el-table-column>
      <el-table-column prop="username" label="姓名" width="120"></el-table-column>
      <el-table-column prop="email" label="邮箱"> </el-table-column>
      <el-table-column prop="mobile" label="电话"> </el-table-column>
      <el-table-column prop="role_name" label="角色"> </el-table-column>
      <el-table-column label="状态" width="80">
        <template slot-scope="scope">
          <el-switch 
            v-model="scope.row.mg_state" 
            @change="userStateChanged(scope.row)"
            :disabled="scope.row.role_name=='超级管理员'"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="username" label="操作">
        <template v-slot:default="{ row }">
          <div>
            <el-tooltip effect="dark" content="编辑信息" placement="top" :enterable="false">
              <el-button
                type="primary"
                size="small"
                icon="el-icon-edit"
                circle
                @click="showEditDialog(row.id)"
              ></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button
                type="success"
                size="small"
                icon="el-icon-s-tools"
                circle
                @click="showRoleDialog(row.id)"
              ></el-button>
            </el-tooltip>
            <el-button
              type="danger"
              size="small"
              icon="el-icon-delete"
              circle
              :disabled="row.role_name=='超级管理员' && row.id==500"
              @click="deleteUser(row.id)"
            ></el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[3, 5, 10, 20]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="queryInfo.total"
      >
      </el-pagination>
    </div>

    <!-- 添加用户信息弹窗 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="40%">
      <el-form
        :model="addUserData"
        :rules="addUserRules"
        ref="addUserData"
        label-width="100px"
        class="demo-addUserData"
        status-icon
        style="padding-right:20px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserData.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUserData.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserData.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addUserData.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAddUser('addUserData')">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户信息弹窗 -->
    <el-dialog title="修改用户信息" :visible.sync="editDialogVisible" width="40%">
      <el-form
        :model="editeUser"
        :rules="editeUserRules"
        ref="editeUser"
        label-width="100px"
        class="demo-editeUser"
        status-icon
        style="padding-right:20px"
      >
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="editeUser.userName" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editeUser.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editeUser.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditeUser('editeUser')">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户权限 -->
    <el-dialog title="分配角色" :visible.sync="roleDialogVisible" width="30%">
      <div class=''>
        <p>当前的用户：{{currentUser.userName}}</p>
        <p>当前的角色：{{currentUser.roleName}}</p>
      </div>
      <div>
        分配新角色
        <el-select v-model="currentUser.roleName" @change='selectRole(currentUser.roleName)' placeholder="请选择">
          <el-option
            v-for="item in roleList"
            :key="item.value"
            :label="item.label"
            :value="item.roleName"
            :disabled="currentUser.roleName=='超级管理员' && currentUser.id==500"
          >
          </el-option>
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="roleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRole(currentUser.roleName)">确 定</el-button>
      </span>
    </el-dialog>
  </el-card>
</template>
<script>
import { Message } from "element-ui";
import {
  api_users_add,
  api_users_get,
  api_users_modifiy,
  api_users_change,
  api_roles_get,
  api_roles_change,
  api_users_delete
} from "./../../api/index";
export default {
  data() {
    // 验证密码
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        callback();
      }
    };
    // 验证手机号的规则
    var checkMobile = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      if (regMobile.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的手机号"));
    };
    return {
      queryInfo:{
        query: "",//查询条件
        pagenum: 1, //当前页码
        pagesize: 3, //每页条数
        total: 0, //总条数
      },
      users: [], // 请求到的用户列表
      addDialogVisible:false,//是否显示添加用户弹窗
      editDialogVisible: false, // 是否显示编辑用户弹窗
      roleDialogVisible:false,//是否显示编辑权限弹窗
      addUserData:{// 添加用户弹窗数据
        username: "",
        password:'',
        email: "",
        mobile: ""
      },
      addUserRules:{// 添加用户弹窗验证规则
        username:[
          { required:true,message: "请输入用户名" },
          { min: 3, max: 10, message: '用户名的长度在3~10个字符之间', trigger: 'blur' }
        ],
        password: [
          { required:true, validator: validatePass, trigger: ['blur','change'] },
          { min: 3, max: 6, message: '密码的长度在3~6个字符之间', trigger: ['blur','change'] }
        ],
        email: [
          { required: true, message: "请输入邮箱地址", trigger: "blur" },
          { type: "email",message: "请输入正确的邮箱地址",trigger: ["blur", "change"] }
        ],
        mobile: [{ required:true, validator: checkMobile, trigger: ["blur", "change"] }]
      },
      editeUser: {// 编辑用户弹窗数据
        id: "",
        userName: "",
        email: "",
        mobile: ""
      },
      editeUserRules: {// 编辑用户弹窗验证规则
        email: [
          { required: true, message: "请输入邮箱地址", trigger: "blur" },
          { type: "email",message: "请输入正确的邮箱地址",trigger: ["blur", "change"] }
        ],
        mobile: [{ validator: checkMobile, trigger: ["blur", "change"] }]
      },
      currentUser:{
        id:'',
        rid:'',//角色id
        userName:'',
        roleName:'',//修改角色权限弹窗 默认值
        roleState:false//是否 临时选择了
      },
      roleList:''// 角色列表
    };
  },
  created() {
    this.get_users();
    this.get_role()
  },
  methods: {
    search(){//  搜索用户
      if(this.queryInfo.query!=''){
        this.queryInfo.pagenum=1
        this.get_users()
      }
    },
    showAddUser(){// 显示添加用户弹窗
      this.addDialogVisible=true
    },
    submitAddUser(formName){//添加用户
      this.$refs[formName].validate(valid => {
        if (valid) {
          api_users_add(this.addUserData).then(res=>{
            console.log(res);
            if(res.meta.status==201){
              Message.success(res.meta.msg)
              this.addDialogVisible=false
              this.get_users()
              this.addUserData.username= ""
              this.addUserData.password=''
              this.addUserData.email= ""
              this.addUserData.mobile= ""
            }else{
              Message.error(res.meta.msg)
            }
          })
        } else {
          return false;
        }
      });
    },
    get_users() {// 获取用户信息
      api_users_get(this.queryInfo).then(res => {
        if (res.meta.status == 200) {
          let { pagenum, total, users } = res.data;
          this.queryInfo.pagenum = pagenum;
          this.queryInfo.total = total;
          this.users = users;
          Message.success(res.meta.msg)
        }
      });
    },
    userStateChanged(currentUser) {//修改用户状态 调用修改用户接口
      api_users_modifiy({
        id: currentUser.id,
        type: currentUser.mg_state
      }).then(res => {
        if (res.meta.status == 200) {
          Message.success(res.meta.msg);
        } else {
          Message.error(res.meta.msg);
        }
      });
    },
    handleSizeChange(val) {// 设置每页 条数
      this.queryInfo.pagesize = val;
      this.get_users();
    },
    handleCurrentChange(val) {// 设置当前页码
      console.log(`当前页: ${val}`);
      this.queryInfo.pagenum = val;
      this.get_users();
    },
    showEditDialog(userId) {
      //显示修改用户信息弹窗 显示时就根据传入id 修改弹窗中输入框绑定的值 为点击当前表格的当前行的数据
      const currentUser = this.users.filter(item => {
        return item.id == userId;
      })[0];
      this.editDialogVisible = true;
      this.editeUser.id = userId;
      this.editeUser.userName = currentUser.username;
      this.editeUser.email = currentUser.email;
      this.editeUser.mobile = currentUser.mobile;
    },
    submitEditeUser(formName) {
      //提交修改后的用户信息 调用更新用户信息接口
      const currentUser = this.users.filter(item => {
        return item.id == this.editeUser.id;
      })[0];
      if (//如果做了修改才验证并提交数据
        currentUser.mobile != this.editeUser.mobile ||
        currentUser.email != this.editeUser.email
      ) {
        let { id, email, mobile } = this.editeUser;
        this.$refs[formName].validate(valid => {
          if (valid) {
            api_users_change({ id, email, mobile }).then(res => {
              //调用更新用户信息接口
              Message.success(res.meta.msg);
              this.get_users(); // 刷新数据列表
              this.editDialogVisible = false; // 关闭弹窗
            });
          } else {
            return false;
          }
        });
      } else {
        Message.warning("未做任何操作");
        this.editDialogVisible = false; // 关闭弹窗
      }
    },
    showRoleDialog(id) {
      //显示修改用户信息弹窗 显示时就根据传入id 修改弹窗中输入框绑定的值 为点击当前表格的当前行的数据
      const currentUser = this.users.filter(item => {
        return item.id == id;
      })[0];
      this.currentUser.id=currentUser.id
      this.currentUser.userName=currentUser.username
      this.currentUser.roleName=currentUser.role_name
      this.roleDialogVisible=true// 显示弹窗
    },
    selectRole(roleName){//改变角色列表下拉框 根据选择的值 更新当前用户的角色id
      const currentRole=this.roleList.filter(item=>{
        return item.roleName==roleName
      })[0]
      this.currentUser.rid=currentRole.id// 更新当前用户角色id
      this.currentUser.roleState=true
    },
    setRole(){//  提交角色更新 操作
      if(this.currentUser.roleState){
        api_roles_change({id:this.currentUser.id,rid:this.currentUser.rid}).then(res=>{
          if(res.meta.status==200){
            Message.success(res.meta.msg)
            this.get_users()
          }else{
            Message.error(res.meta.msg)
          }
          this.roleDialogVisible=false// 隐藏弹窗
        })
      }else{
        Message.warning('未做任何操作')
      }
    },
    get_role(){//请求所有角色信息
      api_roles_get().then(res=>{// 请求所有角色
        if(res.meta.status==200){
          this.roleList=res.data
        }else{
          Message.error(res.meta.msg)
        }
      })
    },
    async deleteUser(id){//删除用户
      console.log(id);
      try{
        await this.$messageBox.confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      const res=await api_users_delete(id)
      if(res.meta.status==200){
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
        this.get_users()
      }else{
        this.$message({
          type: 'info',
          message: res.meta.msg
        });    
      }
      }catch{
        this.$message({
          type: 'info',
          message: '已取消删除'
        }); 
      }

    }
  }
};
</script>
<style>
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}

.box-card {
  width: ;
}
</style>
